<?php

  /*
      n00b's simple HTTP client v0.2
      Copyright (c) 2008 by Ananas || n00b
      All rights reserved
      http://n00bz.biz/
      
      Features:
       - Can perfom HTTP GET
       - Limited perfomance of HTTP POST
       - Limited working with cookies (accept/send).
      
      Todo: - Allow keep-alive connections
            - Coockies upgrade
            - Extend POST capabilities
            
      Modified for TravianParser:
       - Addded internal login check
       - Changed user-agent to gecko/firefox (2.0.0.14)
  */
  
  define("NHTTP_OK", 1);
  
  define("TPARSER_HTTP_PRIMARY", 0);
  define("TPARSER_HTTP_SEC",     2);
  define("TPARSER_HTTP_REM",     0);
  define("TPARSER_HTTP_VERSION", TPARSER_HTTP_PRIMARY.".".TPARSER_HTTP_SEC.".".TPARSER_HTTP_REM);
  define("TPARSER_HTTP_DATE",    1201971600);
  define("TPARSER_HTTP_NAME",    "nHTTP");
  
  // Configuration
  define("USER_AGENT",    "Mozilla/5.0 (Windows; U; Windows NT 5.1; sl; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14");
  define("MAX_REDIRECTS", 5);
  
  // Internal. Do not mess with these if you don't know what ur doing.
  $_forbidden_params = array("mode", "path", "_repeat", "port", "allow_redirect");
  $_cookies = "";

  function _generate_basic_http_request($params)
  {
    global $_forbidden_params;
    $var = "{$params["mode"]} {$params["path"]} HTTP/1.1\r\n";
    if (empty($params["Accept"])) $params["Accept"] = "*/*";
    if (empty($params["Connection"])) $params["Connection"] = "close";
    if (empty($params["User-Agent"])) $params["User-Agent"] = USER_AGENT;
    $piskot = http_return_cookie($params["host"], $params["path"]);
    if (!empty($piskot)) $params["Cookie"] = $piskot;
    foreach ($params as $key => $value)
    {
      // We're not adding internal paramaters to our HTTP request, lol!
      for ($i = 0; $i <= count($_forbidden_params); $i++) if ($key == $_forbidden_params[$i]) continue 2;
      $var .= "$key: $value\r\n";
    }
    return $var;
  }
  
  function _generate_post_http_request($params, $httpar)
  {
    $httpar["Content-Type"] = "application/x-www-form-urlencoded";
    $temp = '';
    foreach ($params as $key => $value)
    {
      if (!empty($temp)) $temp .= '&';
      $temp .= $key."=".rawurlencode($value);
    }
    $httpar["Content-Length"] = strlen($temp);
    $httpar["mode"] = "POST";
    return _generate_basic_http_request($httpar)."\r\n$temp\r\n\r\n";
  }

  function _parse_http_response($response, $host)
  {
    $temp = explode("\r\n", substr($response, 0, strpos($response, "\r\n\r\n")));
    $temp[0] = substr($temp[0], strpos($temp[0], " ") + 1);
    $buffer["response_num"]  = substr($temp[0], 0, strpos($temp[0], " "));
    $buffer["response_text"] = substr($temp[0], strpos($temp[0], " ") + 1);
    for ($i = 1; $i < count($temp); $i++)
    {
      $t = substr($temp[$i], 0, strpos($temp[$i], ":"));
      $buffer[$t] = substr($temp[$i], strpos($temp[$i], " ") + 1);
    }
    $buffer["body"] = substr($response, strpos($response, "\r\n\r\n") + 4);
    if (!empty($buffer["Set-Cookie"])) http_set_cookie($buffer["Set-Cookie"], $host);
    return $buffer;
  }
  
  function _parse_url($url, $params)
  {
    $temp = parse_url($url);
    $params["host"] = $temp["host"];
    $params["port"] = $temp["port"];
    $params["path"] = $temp["path"];
    if (!empty($temp["query"])) $params["path"] .= "?".$temp["query"];
    return $params;
  }
  
  // It's here only to clean code of my other project :-)
  function http_restore_cookies($data)
  {
    global $_cookies;
    $_cookies = $data;
  }
  
  function http_set_cookie($cookie, $domain)
  {
    global $_cookies;
    $__cookie = substr($cookie, 0, strpos($cookie, ";"));
    if (strpos($cookie, "; path="))
    {
      $_path = substr($cookie, strpos($cookie, "; path=") + 7);
      if (strpos($_path, ';')) $_path = substr($_path, 0, strpos($_path, ';'));
    }
    else $_path = "/";
    if (strpos($cookie, "; domain=")) $domain = substr($cookie, strpos($cookie, "; domain=") + 9);
    $_cookies[$domain]["path"] = $_path;
    if (empty($_cookies[$domain]["cookie"])) $_cookies[$domain]["cookie"] = $__cookie;
    else $_cookies[$domain]["cookie"] .= '; '.$__cookie;
  }
  
  function http_return_cookie($domain = NULL, $path = "/")
  {
    global $_cookies;
    if (empty($domain)) return $_cookies;
    if (empty($_cookies)) return;
    foreach ($_cookies as $key => $value)
    {
      if ( ((strpos($domain, $key) !== False) || (strpos($key, $domain) !== False)) &&
           ((strpos($path, $value["path"]) !== False) || ($path == $value["path"]))) return $value["cookie"];
    }
  }
  
  function http_get($url, $params = NULL)
  {
    if ($params["_repeat"] > MAX_REDIRECTS) return False;
    $params = _parse_url($url, $params);
    if (empty($params["port"])) $params["port"] = 80;
    $handle = fsockopen($params["host"], $params["port"]);
    if (!$handle) return False;
    $params["mode"] = "GET";
    fwrite($handle, _generate_basic_http_request($params)."\r\n");
    $buffer = '';
    while (!feof($handle)) $buffer .= fread($handle, 8192);
    fclose($handle);
    $result = _parse_http_response($buffer, $params["host"]);
    if ((($result["response_num"] == 302) || ($result["response_num"] == 301)) && ($params["allow_redirect"]))
    {
      $params["_repeat"]++;
      return http_get($result["Location"], $params);
    }
    else return $result;
  }
  
  function http_post($url, $req = NULL, $params = NULL)
  {
    if ($params["_repeat"] > MAX_REDIRECTS) return False;
    $params = _parse_url($url, $params);
    if (empty($params["port"])) $params["port"] = 80;
    $handle = fsockopen($params["host"], $params["port"]);
    if (!$handle) return False;
    $params["mode"] = "POST";
    fwrite($handle, _generate_post_http_request($req, $params));
    $buffer = '';
    while (!feof($handle)) $buffer .= fread($handle, 8192);
    fclose($handle);
    $result = _parse_http_response($buffer, $params["host"]);
    if ((($result["response_num"] == 302) || ($result["response_num"] == 301)) && ($params["allow_redirect"]))
    {
      $params["_repeat"]++;
      return http_get($result["Location"], $params);
    }
    else return $result;

  }

?>